package com.botarena.server.services;

import java.util.Date;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.botarena.server.dao.BattleDAO;
import com.botarena.server.dao.BattleProcessDAO;
import com.botarena.server.dao.BotDAO;
import com.botarena.server.dao.ContestDAO;
import com.botarena.server.dao.helper.NonTransactional;
import com.botarena.server.dao.helper.NonTransactionalReturn;
import com.botarena.server.model.Contest;

public class AdminService {
	private static final Logger log = Logger.getLogger(AdminService.class.getName());
	
	public int resetDatastore() {
		return DAOService.execute(new NonTransactionalReturn<Integer>() {
			@Override
			public Integer doOutsideTransaction(PersistenceManager pm) {
				//AccountDAO accountDAO = new AccountDAO(pm);
				BattleDAO battleDAO = new BattleDAO(pm);
				BattleProcessDAO battleProcessDAO = new BattleProcessDAO(pm);
				BotDAO botDAO = new BotDAO(pm);
				ContestDAO contestDAO = new ContestDAO(pm);
				
				int total = 0;
				
				log.info("Deleting battle processes...");
				total += battleProcessDAO.deleteAll(500);
				
				log.info("Deleting battles...");
				total += battleDAO.deleteAll(500);
				
				log.info("Deleting bots...");
				total += botDAO.deleteAll(100);
				
				log.info("Deleting contests...");
				total += contestDAO.deleteAll(10);
				
				//log.info("Deleting accounts...");
				//total += accountDAO.deleteAll(100);
				
				log.info("Datastore resetted");
				
				return total;
			}
		});
	}
	
	public void resetAndCreateExampleContent() {
		// Beware !
		resetDatastore();
		
		DAOService.execute(new NonTransactional() {
			
			@Override
			@SuppressWarnings("deprecation")
			public void doOutsideTransaction(PersistenceManager pm) {
				ContestDAO contestDAO = new ContestDAO(pm);
				
				Contest contest = new Contest("Main");
				contest.setActive(true);
				contest.setFrom(new Date());
				contest.setTo(new Date(2011, 11, 11));
				contestDAO.create(contest);
				
			}
		});
	}
}
